package com.yonyou.ucf.mdf.app.controller.interceptor;

import com.yonyou.ucf.mdd.ext.core.AppContext;
import com.yonyoucloud.iuap.ucf.mdd.starter.core.UCFCoreProperties;
import com.yonyoucloud.iuap.ucf.mdd.starter.core.module.mvc.interceptor.AllowConfOriginCorsInterceptor;
import java.util.Arrays;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import static com.yonyou.ucf.mdf.app.controller.isv.AuthController.PATH_AUTH_PREFIX;
import static com.yonyou.ucf.mdf.app.controller.isv.InnerController.PATH_INNER_PREFIX;

/**
 * 本类主要用于
 *
 * @author liuhaoi
 * @since Created At 2020/6/2 11:13 上午
 */
@Component
@RequiredArgsConstructor
public class ISVWebMvcConfigurer implements WebMvcConfigurer {

    private final UCFCoreProperties properties;


    //private final HeaderInterceptor headerInterceptor;

    //private final InnerRequestInterceptor innerRequestInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LocaleInterceptor())
                .addPathPatterns("/**");
        /*registry.addInterceptor(headerInterceptor)
                .addPathPatterns("/**");*/
       /* registry.addInterceptor(cookieValueInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns(PATH_AUTH_PREFIX + "/**")
                .excludePathPatterns(PATH_INNER_PREFIX + "/**");*/
        setISVAllowCorsDomain();
        registry.addInterceptor(new AllowConfOriginCorsInterceptor(properties))
                .addPathPatterns("/**");
    }

    private void setISVAllowCorsDomain(){
        String allowCrossDomain = AppContext.getAppConfig().getProperty("allowCross.Domains");
        if (StringUtils.isNotBlank(allowCrossDomain)){
            String[] allowCorsDomains = properties.getAllowCorsDomains();
            int length = allowCorsDomains.length + 1;
            String[] ISVAllowCorsDomains = Arrays.copyOf(allowCorsDomains,length);
            ISVAllowCorsDomains[length-1] = allowCrossDomain;
            properties.setAllowCorsDomains(ISVAllowCorsDomains);
        }
    }

}
